import axios from "axios";
import { useMainStore } from "../store";
import router from "../router";

import { ElMessage } from "element-plus";

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 30000,
  withCredentials: false, // 禁用 Cookie 等信息
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    let user = localStorage.getItem("loginUserInfo");
    // 自定义请求头
    if (user) {
      user = JSON.parse(user);
      config.headers.token = user.token;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//  响应拦截器
service.interceptors.response.use(
  (response) => {
    let responseCode = response.data.code;
    if (responseCode == 420) {
      router.push("/login");
      return;
    } else if (responseCode === 0) {
      ElMessage.error(response.data.msg || "系统发生错误，请稍后再试！");
    }

    return Promise.resolve(response.data);
  },
  (error) => {
    let { message } = error;

    if (message === "Network Error") {
      ElMessage.error("网络发生错误！");
      return;
    }

    let httpCode = error.response.status;

    if (message.includes("timeout")) {
      message = "请求超时，请稍后重试";
    } else if (httpCode === 420) {
      router.push("/login");
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }

    ElMessage.error(message);
    return Promise.resolve(error);
  }
);

export default service;
